package com.caidan.diagram.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @项目名 MyIntegerceptor
 * @描述 我的拦截器（示例：用户权限校验）
 * @时间 2025/3/20 15:37
 * @作者 小菜蛋
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 处理请求前的逻辑（例如权限校验、日志记录等）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器：请求被拦截 -> " + request.getRequestURI());
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("未授权访问");
            return false; // 拦截请求
        }
        return true; // 放行请求
    }

    /**
     * 处理请求后的逻辑（Controller 执行后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器：请求处理完成");
    }

    /**
     * 处理请求完成后的逻辑（比如清理资源）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器：请求结束");
    }
}
